package dgo.gadgets;
import javax.microedition.lcdui.Graphics;
import starruby.Texture;

public class Window {
  public int width, height;
  private Texture _texture;
  public int x, y, gridSize;
  private Texture _frameTexture;
  Window(int x, int y, int width, int height, Texture texture, int gridSize){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    _texture = texture;
    this.gridSize = gridSize;
   
  }
  
  public Texture getFrameTexture(){
    if(_frameTexture == null){
      int half = gridSize / 2;
      _frameTexture = new Texture(width, height, true);
      int lastI = width / gridSize;
      int lastJ = height / gridSize;

      int srcX = 0;
      int srcY = 0;
      int srcWidth = 0;
      int srcHeight = 0;
      for(int i = 0; i <= lastI; i++){
        for(int j = 0; j <= lastJ; j++){
          srcX = 0;
          srcY = 0;
          // H
          if(i == 0){
            srcWidth = half;
          }else if(i == lastI){
            srcX = half * 3;
            srcWidth = half;
          } else {
            srcX = half;
            srcWidth = gridSize;
          }
          
          // V
          if(j == 0){
            srcHeight = half;
          }else if(j == lastJ){
            srcY = half * 3;
            srcHeight = half;
          } else {
            srcY = half;
            srcHeight = gridSize;
          }
          
          int tx = Math.max(i * gridSize - half, 0);
          int ty = Math.max(j * gridSize - half, 0);
          //System.out.println("i="+i+" j="+j + "HEIGHT" + height + "TY"+ty + "SH"+srcHeight);
          _frameTexture.renderTexture(_texture, tx, ty, srcX, srcY, srcWidth, srcHeight);

          //g.drawTexture(_image, x - srcX, y - srcY, g.LEFT | g.TOP);
        }
      }
    }
    
    return _frameTexture;
  }
  
  public void render(Texture s, int dx, int dy){
    s.renderTexture(_frameTexture, x + dx, y + dy);
  }
        
}
